﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net;
using Top.Api;
using Top.Api.Request;
using Top.Api.Response;
using System.Text;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.IO;
using System.Web.Security;
using AscentExplorer.Models;

namespace AscentExplorer.Controllers
{
    /// <summary>
    /// 用户通过taobao oauth登录成功就启动 TopService ，开始根据当前用户的情况来决定做什么
    /// </summary>
    public class TaobaoController : Controller
    {
        [Authorize]
        public ActionResult Index(string code, string state)
        {
            string userNick = Convert.ToString(Session["taobaoUserNick"]);
            string sessionKey = Convert.ToString(Session["taobaoSessionKey"]);
            TaobaoServiceReference.TaobaoServiceClient client = new TaobaoServiceReference.TaobaoServiceClient("NetNamedPipeBinding_ITaobaoService");
            client.Start(userNick, sessionKey);
            return View();
        }

        public ActionResult Authorize()
        {
            string authorize_url = "https://oauth.taobao.com/authorize";
            string response_type = "code";
            string client_id = "12344956";
            string redirect_uri = "http://www.5content.com/taobao/token";
            string state = string.Empty;

            string url = string.Format("{0}?response_type={1}&client_id={2}&redirect_uri={3}&state={4}", authorize_url, response_type, client_id, redirect_uri, state);
            return Redirect(url);
        }

        public RedirectToRouteResult Token(string code, string state)
        {
            string token_url = "https://oauth.taobao.com/token";
            string grant_type = "authorization_code";
            //string code;
            string redirect_uri = "http://www.5content.com/taobao";
            string client_id = "12344956";
            string client_secret = "3865429228e6ffd6fb132510ed91c2d7";
            string url = string.Format("{0}?grant_type={1}&code={2}&redirect_uri={3}&client_id={4}&client_secret={5}", token_url, grant_type, code, redirect_uri, client_id, client_secret);
            string queryString = string.Format("grant_type={0}&code={1}&redirect_uri={2}&client_id={3}&client_secret={4}", grant_type, code, redirect_uri, client_id, client_secret);

            string accessToken;
            HttpClient client = new HttpClient("https://oauth.taobao.com/");
            string requestUri = "token?" + queryString;
            accessToken = client.Post(requestUri, null).Content.ReadAsString();

            string sessionKey = accessToken.Split(',')[2].Split(':')[1].Replace("\"", "").Replace("}", "").Trim();
            UserGetRequest request = new UserGetRequest();
            request.Fields = "user_id,uid,nick,sex,buyer_credit,seller_credit,location,created,last_visit,birthday,type,status,alipay_no,alipay_account,alipay_account,email,consumer_protection,alipay_bind";
            UserGetResponse response = DoExecute(request, sessionKey, DateTime.Now);
            
            //if (Membership.FindUsersByEmail(response.User.Email) == null)
            //{
                Session["taobaoUserNick"] = response.User.Nick;
                Session["taobaoSessionKey"] = sessionKey;
                ProfileCommon profileCommon = (ProfileCommon)ProfileCommon.Create(response.User.Email);
                profileCommon.TaobaoUser = response.User;
                FormsAuthentication.SetAuthCookie(response.User.Nick, true);
                return RedirectToAction("Index", "Taobao");
            //}
        }

        private T DoExecute<T>(ITopRequest<T> request, string session, DateTime timestamp) where T : TopResponse
        {
            string serverUrl = "http://gw.api.taobao.com/router/rest";
            string appKey = "12344956";
            string appSecret = "3865429228e6ffd6fb132510ed91c2d7";
            ITopClient client = new DefaultTopClient(serverUrl, appKey, appSecret);
            return client.Execute(request, session, timestamp);            
        }
    }
}